const express = require("express");
const router = express.Router();

const { timeTrans } = require("../../../utils");
const {
  getNotice,
  addNotice,
  updateNotice,
  deleteNotice,
  showNotice,
} = require("../../../model/weixin/admin/notice");

/* notice增删改查 */

// 查找notice数据
router.get("/", async function (req, res, next) {
  let data = await getNotice();
  res.send(data);
});

// 添加notice数据
router.post("/add", async (req, res, next) => {
  const notice_id = Number(req.body.notice_id);
  const text = req.body.text;
  const atime = timeTrans(req.body.atime);
  // console.log(notice_id, text, atime);
  addNotice([notice_id, text, atime])
    .then(() => {
      res.send({
        code: 200,
        msg: "添加广告轮播成功",
      });
    })
    .catch((err) => {
      res.send({
        code: 500,
        msg: "添加广告轮播失败",
        err,
      });
    });
});

// 修改notice数据
router.post("/update", (req, res, next) => {
  const notice_id = Number(req.body.notice_id);
  const text = req.body.text;
  const atime = timeTrans(req.body.atime);
  updateNotice([text, atime, notice_id])
    .then(() => {
      res.send({
        code: 200,
        msg: "修改广告轮播成功",
      });
    })
    .catch((err) => {
      res.send({
        code: 500,
        msg: "修改广告轮播失败",
        err,
      });
    });
});

// 删除单个notice
router.get("/delete", (req, res, next) => {
  // console.log(req.query);
  const notice_id = Number(req.query.notice_id);
  deleteNotice([notice_id])
    .then(() => {
      res.send({
        code: 200,
        msg: "删除图片成功",
      });
    })
    .catch((err) => {
      res.send({
        code: 500,
        msg: "删除图片失败",
      });
    });
});

// 是否展示广告文本
router.get("/show", (req, res, next) => {
  // console.log(req.query);
  const isNotice = req.query.isNotice === "false" ? false : true;
  const notice_id = Number(req.query.notice_id);

  showNotice([isNotice, notice_id])
    .then(() => {
      res.send({
        code: 200,
        msg: "修改成功",
      });
    })
    .catch((err) => {
      res.send({
        code: 500,
        msg: "修改失败",
      });
    });
});
module.exports = router;
